﻿using ServerSide.EFCoreContext;
using ServerSide.Model;
using ServerSide.Model.Dto.RoleDto;
using ServerSide.Model.Other;
using ServerSide.Service.Interface;
using ServerSide.utils;

namespace ServerSide.Service
{
    public class RoleService : IRoleService
    {
        private readonly MyDBContext _myDBContext;
        public RoleService(MyDBContext myDBContext) {
            _myDBContext = myDBContext;
        }
        /// <summary>
        /// 编辑菜单权限时需要获取当前用户拥有的菜单id信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<int> GetMenuIdByRoleId(int id)
        {
            List<int> MenuIds = _myDBContext.RoleMenu.Where(item => item.RoleId == id).Select(item => item.MenuId).ToList();
            return MenuIds;
        }
        /// <summary>
        /// 获取角色表所有数据
        /// </summary>
        /// <param name="roleRequest"></param>
        /// <returns></returns>
        public PageInfo GetRole(RoleRequest roleRequest)
        {
            PageInfo pageInfo = new();

            int pageNumber = string.IsNullOrEmpty(roleRequest.Page.ToString()) ? 1 : roleRequest.Page;
            int pageSize = string.IsNullOrEmpty(roleRequest.Size.ToString()) ? 10 : roleRequest.Size;

            IQueryable<Role> query = _myDBContext.Role;
            if (!string.IsNullOrEmpty(roleRequest.RoleName))
            {
                query = query.Where(item => item.Name.Contains(roleRequest.RoleName));
            }
            //根据RoleSort进行升序排序
            query = query.OrderBy(item => item.RoleSort);

            List<Role> roles = query.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();

            pageInfo.Total = query.Count();
            pageInfo.DataList = roles;


            return pageInfo;
        }

        public bool AddRole(Role role)
        {
            bool roleExist = _myDBContext.Role.Where(item => item.Name == role.Name||item.Description==role.Description).Any();
            if (!roleExist)
            {
                role.CreateTime=GenerateTime.GetCurrentTime();
                _myDBContext.Role.Add(role);
                int execSuccess = _myDBContext.SaveChanges();
                if (execSuccess > 0)
                {
                    return  true;
                }
            }
            return false;
        }

        public bool BatchDelRoles(List<int> ids)
        {
            try
            {
                List<Role> roles = _myDBContext.Role.Where(item => ids.Contains(item.Id)).ToList();

                _myDBContext.Role.RemoveRange(roles);
                int v = _myDBContext.SaveChanges();
                if (v > 0)
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;

            }

        }

        public bool DelRole(Role role)
        {
            bool exist = _myDBContext.Role.Any(item => item.Id == role.Id);
            if (exist)
            {
                _myDBContext.Role.Remove(role);
                int execSuccess = _myDBContext.SaveChanges();
                if (execSuccess > 0)
                {
                    return true;
                }
            }
            return false;
        }

        public bool UpdateRole(Role role)
        {
            Role? roleData = _myDBContext.Role.Where(item => role.Id == item.Id).FirstOrDefault();
            if (roleData != null)
            {
                roleData.Name = role.Name;
                roleData.Description = role.Description;
                roleData.RoleSort = role.RoleSort;
                roleData.Enable = role.Enable;
                try
                {
                    _myDBContext.Role.Update(roleData);
                    int rowsAffected = _myDBContext.SaveChanges();

                    if (rowsAffected > 0)
                    {
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    // 处理异常
                    Console.WriteLine($"An error occurred: {ex.Message}");
                }
            }
            return false;
        }
        /// <summary>
        /// 更新角色是否启用
        /// </summary>
        /// <param name="id"></param>
        /// <param name="enable"></param>
        /// <returns></returns>
        public bool UpdateRoleEnable(int id, int enable)
        {
            Role? role = _myDBContext.Role.Where(item => item.Id == id).FirstOrDefault();
            if (role != null)
            {
                if (enable == 1 || enable == 0)
                {
                    role.Enable = enable;
                }
                _myDBContext.Role.Update(role);
                int v = _myDBContext.SaveChanges();
                if (v > 0)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 角色更新拥有的菜单权限-RoleMenu表
        /// </summary>
        /// <param name="roleMenuRequest"></param>
        /// <returns></returns>
        public bool UpdataRoleMenuScope(RoleMenuRequest roleMenuRequest)
        {
            //存在的全删除
            List<RoleMenu> roleMenus = _myDBContext.RoleMenu.Where(item => item.RoleId == roleMenuRequest.RoleId).ToList();
            _myDBContext.RemoveRange(roleMenus);
            //重新添加权限数据
            List<RoleMenu> addRoleMenus = roleMenuRequest.MenuIds.Select(menuId => new RoleMenu
            {
                RoleId = roleMenuRequest.RoleId,
                MenuId = menuId,
            }).ToList();
            _myDBContext.RoleMenu.AddRange(addRoleMenus);

            int saveSucc = _myDBContext.SaveChanges();
            if (saveSucc>0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 新增、编辑用户时获取所有的角色信息
        /// </summary>
        /// <returns></returns>
        public List<Role> GetRoleList()
        {
            List<Role> roles = _myDBContext.Role.Where(item=>item.Enable==1).ToList();
            if (roles.Count > 0)
            {
                return roles;
            }
            return null;
        }
        /// <summary>
        /// 编辑用户时需要回显当前用户拥有的角色id信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<int> GetRoleListByUId(int? userId)
        {

            List<int> list = _myDBContext.UserRole
                .Where(ur => ur.UserId == userId).
                Join(_myDBContext.Role,
                     ur => ur.RoleId,
                     r => r.Id,
                     (ur, r) => r)
                .Where(r => r.Enable == 1).Select(r => r.Id).ToList();
            return list;
        }
    }
}
